package view;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DecimalFormat;

import model.TemperatureModel;

public abstract class TemperatureView implements java.util.Observer {
	
	@SuppressWarnings("unused")
	protected String label;
	protected TemperatureModel model;
	protected Frame temperatureFrame;
	protected TextField display = new TextField();
	protected Button raiseTempButton = new Button("Raise");
	protected Button lowerTempButton = new Button("Lower");
	
	TemperatureView() {}
	
	public void initialize(TemperatureModel model, int h, int v) {
		this.model = model;
		temperatureFrame = new Frame(label);
		temperatureFrame.add("North", new Label(label));
		temperatureFrame.add("Center", display);
		Panel buttons = new Panel();
		buttons.add(raiseTempButton);
		buttons.add(lowerTempButton);
		temperatureFrame.add("South", buttons);
		temperatureFrame.addWindowListener(new CloseListener());
		model.attach(this); // Connect the View to the Model
		temperatureFrame.setSize(160, 120);
		temperatureFrame.setLocation(h, v);
		temperatureFrame.setVisible(true);
	}

	public void setDisplay(String s) {
		display.setText(s);
	}

	public double getDisplay() {
		double result = 0.0;
		try {
			result = Double.valueOf(display.getText()).doubleValue();
		} catch (NumberFormatException e) {
			// Do nothing
		}
		return result;
	}

	public void addDisplayListener(ActionListener a) {
		display.addActionListener(a);
	}

	public void addRaiseTempListener(ActionListener a) {
		raiseTempButton.addActionListener(a);
	}

	public void addLowerTempListener(ActionListener a) {
		lowerTempButton.addActionListener(a);
	}

	protected TemperatureModel model() {
		return model;
	}

	public static class CloseListener extends WindowAdapter {
		public void windowClosing(WindowEvent e) {
			e.getWindow().setVisible(false);
			System.exit(0);
		}
	}
	
	public TemperatureModel getModel(){
		return this.model;
	}
	
	protected String getFormatedT(double temp) {
		return new DecimalFormat("#.##").format(temp);
	} 
}
